package com.xuecheng.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.auth.service.AuthService;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Author:王亚栋
 * @Date:2023/8/14 22:12
 * @Version:1.0
 * 账号名密码登录认证
 */
@Service("password_authService")
@Slf4j(topic = "PasswordAuthServiceImpl")
public class PasswordAuthServiceImpl implements AuthService {

    @Autowired
    private XcUserMapper xcUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {

        String username = authParamsDto.getUsername();
        log.info("接收到登录用户的用户名为:{}",username);

        //TODO 校验验证码

        //账号是否存在
        LambdaQueryWrapper<XcUser> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(XcUser::getUsername,username);

        XcUser xcUser = xcUserMapper.selectOne(queryWrapper);
        log.info("登录时从数据库获取到的用户信息:{}",xcUser);

        if (xcUser == null){

            throw new RuntimeException("账号不存你在！");
        }

        //验证密码是否正常
        String passwordDb = xcUser.getPassword();
        log.info("从数据库中获取到的用户密码:{}",passwordDb);

        //拿到用户输入的密码
        String authPassword = authParamsDto.getPassword();
        log.info("用户输入的密码:{}",authPassword);

        //校验密码
        boolean matches = passwordEncoder.matches(authPassword, passwordDb);

        if (!matches){

            throw new RuntimeException("账号或密码错误！");
        }

        XcUserExt xcUserExt = new XcUserExt();

        BeanUtils.copyProperties(xcUser,xcUserExt);

        return xcUserExt;
    }
}
